package com.mark.service.impl;

import com.mark.common.Const;
import com.mark.common.ServerResponse;
import com.mark.dao.SellerMapper;
import com.mark.dao.UserMapper;
import com.mark.enums.UserStateEnum;
import com.mark.exception.SellerException;
import com.mark.pojo.Seller;
import com.mark.pojo.User;
import com.mark.service.ISellerService;
import com.mark.util.JsonUtil;
import com.mark.util.RedisShardedPoolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by Choisaaaa on 2018/5/22.
 * 店家信息处理业务逻辑
 */

@Service("iSellerService")
public class SellerServiceImpl implements ISellerService {
    @Autowired
    private SellerMapper sellerMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public ServerResponse<String> register(Seller seller, String loginToken) {
        try {
            int resultCount = sellerMapper.insert(seller);
            if (resultCount > 0) {
                User user = new User();
                user.setId(seller.getUserId());
                user.setRole(UserStateEnum.SELLER_CUSTOMER.getRole());//设置注册身份为普通用户
                resultCount = userMapper.updateByPrimaryKeySelective(user);
                if (resultCount > 0) {
                    User currentUser = userMapper.selectByPrimaryKey(seller.getUserId());
                    //因为升级为店家User的角色，seller的相关操作需要根据role进行判断。所以需要重新更新Redis中user的信息
                    RedisShardedPoolUtil.setEx(loginToken, JsonUtil.obj2String(currentUser), Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
                    return ServerResponse.createBySuccessMessage("注册成功！");
                }
            }
            return ServerResponse.createByErrorMessage("注册失败！");
       } catch (Exception e){
            throw new SellerException("register",e.getClass()+e.getMessage());
        }
    }

}
